package com.woniuxy.hrm.consumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.woniuxy.hrm.entity.Order;

import com.woniuxy.hrm.mapper.OrderMapper;

import com.woniuxy.hrm.util.RabbitmqConst;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 重复消费
 *  消费者消费完了，应答通过网络发出但是因为网络波动原因队列没有没收到，导致消费者重复消费消息
 *  解决方法
 *  1.在生产者发送消息时，获取该信息的唯一信息，存入redis中
 *  2.在消费者消费信息时，先去删除redis的数据，删除成功才能消费，删除不成功则不能消费
 *
 *
 */
@Component
public class AddOrderConsumer {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @RabbitListener(queues = RabbitmqConst.ADD_ORDER_QUEUE)
    public void receive(String msg, Channel channel, Message message) {

        try {
            Order order = JSON.parseObject(msg, Order.class);
            if (redisTemplate.delete(order.getOrderNum())) {
                System.out.println(order);
                orderMapper.addOrder(order);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false );
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }
}
